<template>
    <div class="warpper-box">
      <div class="inner_box">
       <form-create 
       v-model="params.fApi" 
       :rule="params.rule" 
       :option="params.option" 
       @btn-search-click="loadList(true)" 
       @btn-add-click="add(true)" 
       @btn-download-click="downloadProjectExecl"
       @btn-export-click="exportProjectExecl"
       @btn-import-click="importProjectExecl"
       @btn-del-batch-click="delBatchProjectClick"
       @btn-reset-click="reset"/>
       <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="fileExcel" @change="handleChange" style="display: none;" />
      <project-list
       :key="keys"
       :tableData="tables.tableData" 
       :tableLabel="tables.tableLabel" 
       :models="tables" 
       @on-search-click="loadList"
       @on-selection-click="selectionChange"
       @on-edit-click="add"
       @on-del-click="del"
       />
       <el-dialog :title="form.title" :visible.sync="form.visible" :width="form.width" :close-on-click-modal="false">
        <form-create 
        v-model="form.fApi" 
        :rule="form.rule" 
        :option="form.option" />
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="form.visible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="onFormSubmit">保存</el-button>
        </div>
      </el-dialog>
      </div>
    </div>
  </template>
  
  <script>
  import { PARAMS_PROJECT,FORM_PROJECT,LABEL_PROJECT,OPTION_BLOCK,OPTION_INLINE} from "./projectModel/project_form"
  import ProjectList from "./projectModel/project_model_list"
  import {getProjectList,saveProjectSave,delProject,delBatchProject,importExcelProject} from "@/api/project_api"
  import { xlsx } from "@/utils/xlsx"
  export default {
    components:{
        ProjectList
    },
    data() {
      return {
        keys:0,
        params:{
          fApi:{},
          rule:PARAMS_PROJECT,
          option:OPTION_INLINE
        },
        tables:{
          total:0,
          hackReset:true,
          fixed:'right',
          width:'160',
          tableData:[],
          tableLabel: LABEL_PROJECT
        },
        form:{
          id:'',
          title:'新增项目库',
          width:"500px",
          visible:false,
          fApi:{},
          rule:[],
          option:OPTION_BLOCK
        },
        page:{
          pageNum:1,
          pageSize:10,
        },
        selectItem:[]
      };
    },
    mounted() {
      this.loadList(true);
      this.$nextTick(()=>{
        this.params.fApi.setValue({"name":"","receiverPhone":""});
      })
    },
    methods: {
      async loadList(formData) {
        let params = {};
        let query = this.params.fApi.bind();
        params.name = query.name;
        params.receiverPhone = query.receiverPhone;
        if(formData !== undefined && formData.type === 'page'){
          this.page.pageNum = formData.pageNum;
          this.page.pageSize = formData.pageSize;
        }
        if(formData===true){
          this.page.pageNum = 1;
          this.keys++;
        }
        params.pageNum = this.page.pageNum;
        params.pageSize = this.page.pageSize;
        const req = await getProjectList(params);
        this.tables.tableData = req?.data?.list ?? [];
        this.tables.tableData.forEach(v=>{
          v.edit=true;v.del=true;
        })
        this.tables.hackReset = false;
        this.$nextTick(()=>{
          this.tables.hackReset = true;
        });
        this.tables.total = req?.data?.total ?? 0;
      },
      
      add(row){
        this.form.rule = FORM_PROJECT;
        this.$nextTick(()=>{
          if(row === true){
            this.form.title = "新增";
            this.form.id = "";
            this.form.fApi.resetFields();
          }else{
            this.form.title = "编辑";
            this.form.id = row.id;
            this.form.fApi.setValue({
              "name":row.name,
              "receiverName":row.receiverName,
              "receiverPhone":row.receiverPhone,
              "address":row.address,
              "remarks":row.remarks
            })
          }
        })
        this.form.visible = true;
      },
      async onFormSubmit(formData) {
        this.form.fApi.submit(async (formData, $f) => {
          try {
            let text = "新增成功";
            if(this.form.id){
              formData.id = this.form.id;
              text = "修改成功"
            }
            if(formData.remarks === ""){
              formData.remarks = " ";
            }
            const req = await saveProjectSave(formData);
            if(req.code === 200){
              this.$message.success(text);
              this.form.visible = false;
              this.loadList();
            }
          } catch (error) {
            //this.$message.info(JSON.stringify(error));
          }
        })
      },
      del(row){
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          const req = await delProject(row.id);
          if(req.code === 200){
            this.$message.success("删除成功");
            this.loadList(true);
          }
        }).catch(() => {});
      },
      selectionChange(arr){
        this.selectItem = arr;
      },
      downloadProjectExecl(){
        window.open("/file/项目库模版.xlsx","_blank");
      },
      delBatchProjectClick(){
        if(this.selectItem.length === 0){
            return this.$message.error("请勾选要删除的数据！");
        }
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          let ids = [];
          this.selectItem.forEach(v=>{
            ids.push(v.id)
          })
          const req = await delBatchProject(ids);
          if(req.code === 200){
            this.$message.success("操作成功");
            this.loadList(true);
          }
        }).catch(() => {});
      },
      importProjectExecl(){
        this.$refs.fileExcel.click()
      },
      async handleChange(e){
          e.preventDefault();
          let _this = this;
          let file = e.target.files[0];
          if(file===undefined){return;}
          if (file.name.indexOf('.xls') === -1) {
              _this.$message.error("只支持xls格式");
              e.target.value= "";
              return;
          }
          let formData = new FormData();
          formData.append("file",file);
          const req = await importExcelProject(formData);
          e.target.value= "";
          if(req.code === 200){
            this.$message.success("导入成功");
            this.loadList(true);
          }
          
      },
      exportProjectExecl(){
        if(this.selectItem.length === 0){
            return this.$message.error("请勾选要导出的数据！");
        }
        let fields = {
          title0: "编号",
          title1: "项目名称",
          title2: "项目联系人",
          title3: "联系电话",
          title4: "项目地点",
          title5: "备注"
        };
        let arry = [];
        let i = 0;
        this.selectItem.forEach(ele => {
            i++;
            arry.push({
                title0: i,
                title1: ele.name,
                title2: ele.receiverName,
                title3: ele.receiverPhone,
                title4: ele.address,
                title5: ele.remarks
            });
        });

         const manualWidthColumns = [
          { width: 10 },
          { width: 50 },
          { width: 20 },
          { width: 20 },
          { width: 50 },
          { width: 50 }
        ];

        xlsx(arry, fields,manualWidthColumns, "项目库列表");
        this.loadList(true);
      },
      reset(){
        this.params.fApi.resetFields();
        this.loadList(true);
      }
    }
  };
  </script>